<?php
/**
 * Copyright (c) 2020
 * 摘    要：
 * 作    者：san
 * 修改日期：2020.03.30
 */

namespace App\Controller\Http;

use App\Constants\Constants;
use App\Library\Traits\Helper;
use App\Model\Role;
use ErrorException;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Collection;
use Hyperf\Database\Model\Model;
use Hyperf\DbConnection\Db;
use Hyperf\Utils\ApplicationContext;

class RoleController extends BaseController
{
    /**
     * 角色列表
     */
    public function index()
    {
        $show = $this->request->input('show', false);

        if ($show) {
            $condition = [];
        } else {
            $condition = [['id', '<>', 1]];
        }

        $result = Role::query()
            ->where($condition)
            ->get()->toArray();

        return $this->response->showResults(Constants::RETURN_SUCCESS, 'SUCCESS', $result);
    }


    public function getPermissions()
    {
        $id = $this->request->input('id');

        $roles = Db::table('role_has_permissions')
            ->select('permission_id')
            ->where('role_id', $id)
            ->get()->toArray();

        $tmp = [];
        foreach ($roles as $key => $value) {
            $value = object2array($value);
            $tmp[] = $value['permission_id'];
        }

        return $this->response->showResults(Constants::RETURN_SUCCESS, 'SUCCESS', $tmp);
    }

    /**
     * 更新
     */
    public function update()
    {
        try {
            $rules = [
                'id'          => 'required',
                'name'        => 'required',
                'description' => 'required',
            ];

            $this->validator($rules);

            $id          = $this->request->input('id');
            $name        = $this->request->input('name');
            $description = $this->request->input('description');

            $role = $this->_checkExits($id);

            $role->name        = $name;
            $role->description = $description;
            $role->save();

            return $this->response->showResults(Constants::RETURN_SUCCESS, t('message.12001'), []);
        } catch (\Exception $exception) {
            return $this->response->showResults(Constants::SERVER_ERROR, $exception->getMessage(), []);
        }
    }

    /**
     * 角色赋权
     */
    public function permission()
    {
        try {
            $rules = [
                'id'          => 'required',
                'permissions' => 'required',
            ];

            $this->validator($rules);
            $id          = $this->request->input('id');
            $permissions = $this->request->input('permissions');

            if (!is_array($permissions)) {
                $permissions = json_decode($permissions, true);
                $permissions = $permissions['checked'];
            }

            $this->_checkExits($id);
            Db::table('role_has_permissions')->where('role_id', $id)->delete();
            if ($permissions) {
                $permissions = array_unique($permissions);
                foreach ($permissions as $key => $value) {
                    $permissions[$key] = (int)$value;
                }
                ApplicationContext::getContainer()->get(Role::class)->setAttribute('id', (int)$id)->givePermissionTo($permissions);
            }
            return $this->response->showResults(Constants::RETURN_SUCCESS, t('message.12001'), []);
        } catch (\Exception $exception) {
            return $this->response->showResults(Constants::SERVER_ERROR, $exception->getMessage(), []);
        }
    }

    /**
     * @param $id
     * @throws ErrorException
     * @return Builder|Builder[]|Collection|Model|null
     */
    private function _checkExits($id)
    {
        $role = Role::query()->find($id);

        if (!$role) {
            throw new ErrorException(t('message.12058'));
        }

        return $role;
    }
}
